<?php

namespace S\WeChat\Util;

use S\Cache\Cache as SCache;


/**
 * EasyWeChat兼容的缓存
 *
 * 实现了\Doctrine\Common\Cache\Cache的缓存.
 * 尽量不要直接调用这个类,通过\Ext\Wechat\Application::cache()方法调用,可以省去include自动加载文件的操作.
 *
 * @package Ext\Wechat\Util
 */
class Cache implements \Doctrine\Common\Cache\Cache
{

    protected $type = SCache::TYPE_DEFAULT;
    protected $name = SCache::NAME_DEFAULT;
    protected $pool = null;

    final public function __construct($type = SCache::TYPE_DEFAULT, $name = SCache::NAME_DEFAULT)
    {
        $this->setType($type)->setName($name);
    }

    public function fetch($id)
    {
        return Serializer::decode($this->getPool()->get($id));
    }

    public function contains($id)
    {
        return !empty($this->fetch($id));
    }

    public function save($id, $data, $lifeTime = 0)
    {
        return $this->getPool()->set($id, Serializer::encode($data), $lifeTime);
    }

    public function delete($id)
    {
        return $this->getPool()->del($id);
    }

    public function getStats()
    {
        return null;
    }

    protected function setType($name)
    {
        $this->type = $name;
        return $this;
    }

    protected function getType()
    {
        return $this->type;
    }

    protected function setName($name)
    {
        $this->name = $name;
        return $this;
    }

    protected function getName()
    {
        return $this->name;
    }

    /**
     * @return \S\Cache\Handler\Abstraction
     * @throws \Exception
     */
    protected function getPool()
    {
        return SCache::pool($this->getType(), $this->getName());
    }


}